<?php
/**
 * 核心类
 * @author moyung <moyung@wittystudio.com>
 * @copyright Copyright(C) 2013 wittystudio.com
 * @license http://git.oschina.net/wittystudio/wechatmp/blob/master/LICENSE
 */

class Wechatmp {

    /**
     * @var string 由数字与字母组成，长度介于3-32之间
     */
    private $token;

    /**
     * 文字消息模板
     */
    const TEXTTPL = "<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[text]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		<FuncFlag>%s</FuncFlag>
		</xml>";

    /**
     * 语音消息模板
     */
    const MUSICTPL = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[music]]></MsgType>
        <Music>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
        </Music>
        <FuncFlag>%s</FuncFlag>
        </xml>";

    /**
     * 图文消息模板（主体部分）
     */
    const NEWSMAINTPL = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <ArticleCount>%s</ArticleCount>
        <Articles>%s</Articles>
        <FuncFlag>%s</FuncFlag>
        </xml>";

    /**
     * 图文消息模板（子条目）
     */
    const NEWSITEMTPL = "<item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
        </item>";

    /**
     * 创建对象时初始化token
     *
     * @param string $token 如不提供默认为空串
     */
    function __construct($token = '')
    {
        $this->token = $token;

    }

    /**
     * 系统认证入口
     *
     * echostr不为空，判写为初次配置，返回echostr
     * 为空，则调用responseMsg方法
     */
    public function valid()
    {
        if($this->checkSignature()){
            $echoStr = $_GET["echostr"];
            if(!empty($echoStr))
            {
                echo $echoStr;
                exit;
            }else{
                $this->responseMsg();
            }

        }
    }

    /**
     *
     * 用户身份认证(取自开发接口示例)
     *
     * @return bool 成功返回true，否则返回false
     */
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = $this->token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        return $tmpStr == $signature;
    }

    /**
     * 根据用记提交的内容，完成响应处理
     */
    private  function responseMsg()
    {

        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)){

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $msgType = $postObj->MsgType;
            $time = time();

            switch($msgType)
            {
                case "text":

                    $keyword = trim($postObj->Content);

                    if(!empty( $keyword ))
                    {
                        $contentStr = "Welcome to wechat world!";
                        $funcFlag = 0;

                        $resultStr = sprintf(self::TEXTTPL, $fromUsername, $toUsername, $time, $contentStr,$funcFlag);

                        echo $resultStr;
                    }

                    break;
                case "music":

                    break;
                case "image":

                    break;
                case "link":

                    break;
                case "location":

                    break;
                case "event":

                    $event = $postObj->Event;

                    switch($event)
                    {
                        case "subscribe":

                            break;
                        case "unsubscribe":

                            break;
                        case "CLICK":

                            $eventkey = $postObj->EventKey;

                            break;

                    }
                    break;

            }

        }
    }
}